//
//  MasterWebViewController.m
//  HiMaster3
//
//  Created by jinghao on 16/1/12.
//  Copyright © 2016年 jinghao. All rights reserved.
//

#import "MasterWebViewController.h"
#import <WebKit/WebKit.h>

@interface MasterWebViewController ()<UIWebViewDelegate,UIActionSheetDelegate>
{
    NSTimer *_timer;	// 用于UIWebView保存图片
    int _gesState;	  // 用于UIWebView保存图片
    NSString *_imgURL;  // 用于UIWebView保存图片
}

@property (nonatomic,strong)WKWebView *mWkWebView;
@property (nonatomic,strong)UIWebView *mWebView;
@property (nonatomic,strong)UIBarButtonItem *closeWebViewItem;
@property (nonatomic,strong)UIBarButtonItem *shareButtonItem;
@property (nonatomic,strong)NSDictionary *shareDict;
@property (nonatomic,strong)UIActivityIndicatorView *activityIndicatorView;


@end


static NSString* const kTouchJavaScriptString=
@"document.ontouchstart=function(event){\
x=event.targetTouches[0].clientX;\
y=event.targetTouches[0].clientY;\
document.location=\"myweb:touch:start:\"+x+\":\"+y;};\
document.ontouchmove=function(event){\
x=event.targetTouches[0].clientX;\
y=event.targetTouches[0].clientY;\
document.location=\"myweb:touch:move:\"+x+\":\"+y;};\
document.ontouchcancel=function(event){\
document.location=\"myweb:touch:cancel\";};\
document.ontouchend=function(event){\
document.location=\"myweb:touch:end\";};";

// 用于UIWebView保存图片
enum
{
    GESTURE_STATE_NONE = 0,
    GESTURE_STATE_START = 1,
    GESTURE_STATE_MOVE = 2,
    GESTURE_STATE_END = 4,
    GESTURE_STATE_ACTION = (GESTURE_STATE_START | GESTURE_STATE_END),
};

@implementation MasterWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftItemsSupplementBackButton = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.mWebView];
    [self.view addSubview:self.activityIndicatorView];
    [self.mWebView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(44, 0, 0, 0));
    }];
    
    [self.activityIndicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    
    [self loadRequest];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [self addNotifications];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeNotifications];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    self.mWebView = nil;
}


- (void)addNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLoginNotification:) name:MasterUserLoginNotification object:nil];
}

- (void)removeNotifications{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MasterUserLoginNotification object:nil];
}

- (void)userLoginNotification:(id)sender{
    if (self.mWebView.canGoBack) {
        [self.mWebView reload];
    }else{
        [self loadRequest];
    }
}

- (BOOL)canGotoBack
{
    if ([self.mWebView canGoBack]) {
        if (self.navigationItem.leftBarButtonItems.count<2) {
            [self.navigationItem addLeftBarButtonItem:self.closeWebViewItem animated:TRUE];
        }
        [self.mWebView goBack];
        return FALSE;
    }else{
        return TRUE;
    }
}

- (void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIActivityIndicatorView*)activityIndicatorView
{
    if(!_activityIndicatorView){
        _activityIndicatorView = [[UIActivityIndicatorView alloc] init];
        _activityIndicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        _activityIndicatorView.hidesWhenStopped = YES;
    }
    return _activityIndicatorView;
}

- (UIBarButtonItem*)closeWebViewItem{
    if (!_closeWebViewItem) {
        _closeWebViewItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    }
    return _closeWebViewItem;
}

- (UIWebView*)mWebView{
    if (!_mWebView) {
        _mWebView = [[UIWebView alloc] init];
        _mWebView.delegate = self;
        _mWebView.opaque = NO;
        _mWebView.backgroundColor = [UIColor clearColor];
    }
    return _mWebView;
}

- (void)loadRequest {
    if (! [@"http" isEqualToString:[self.url protocol]]) {
        self.url = [NSURL URLWithString:[self.params objectForKey:@"url"]];
    }
    NSMutableURLRequest *requestObj = [NSMutableURLRequest requestWithURL:self.url];
    
    [requestObj addMasterHeadInfo];
        
    [self.mWebView loadRequest:requestObj];
}

- (UIBarButtonItem*)shareButtonItem
{
    if (!_shareButtonItem) {
        _shareButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Share_icon"] style:UIBarButtonItemStylePlain target:self action:@selector(shareButtonOnClick:)];
    }
    return _shareButtonItem;
}

- (void)shareButtonOnClick:(id)sender{
    if(self.shareDict){
        [self shareContentOfApp:self.shareDict];
    }
}

- (void)setShareDict:(NSDictionary *)shareDict
{
    _shareDict = shareDict;
    if (shareDict) {
        [self.navigationItem setRightBarButtonItem:self.shareButtonItem animated:YES];
    }else{
        self.navigationItem.rightBarButtonItem = nil;
    }
}

#pragma mark -- UIWebViewDelegate

//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
//{
//    NSString *urlString = request.URL.absoluteString;
//    if ([urlString hasPrefix:@"master:"]) {
//        UIViewController* vct = [self.urlManager viewControllerWithUrl:urlString];
//        if (vct) {
//            [self pushViewController:vct animated:YES];
//            return NO;
//        }
//    }
//    return YES;
//}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [self.activityIndicatorView startAnimating];
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self.activityIndicatorView stopAnimating];
}

// 网页加载完成时触发
#pragma mark UIWebDelegate implementation
- (void)webViewDidFinishLoad:(UIWebView*)theWebView
{
    // Black base color for background matches the native apps
//    theWebView.backgroundColor = [UIColor blackColor];
    
    [self.activityIndicatorView stopAnimating];
    
    NSString *title = [theWebView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if(![title isEmpty]){
        self.title=title;
    }
    
    NSString *shareJson = [theWebView stringByEvaluatingJavaScriptFromString:@"app_share();"];
    if (shareJson && [shareJson isKindOfClass:[NSString class]] && shareJson.length>0) {
        self.shareDict = [NSJSONSerialization JSONObjectWithData:[shareJson dataUsingEncoding:NSUTF8StringEncoding]
                                                         options:NSJSONReadingMutableContainers
                                                           error:nil];
    }else{
        self.shareDict = nil;
    }
    NSLog(@"======shareJson===========%@",shareJson);
    // 当iOS版本大于7时，向下移动20dp
//    if (!IOS7) { }
    
    // 防止内存泄漏
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    
    // 响应touch事件，以及获得点击的坐标位置，用于保存图片
//    [theWebView stringByEvaluatingJavaScriptFromString:kTouchJavaScriptString];

//    [super webViewDidFinishLoad:theWebView];
}

// 功能：UIWebView响应长按事件
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)_request navigationType:(UIWebViewNavigationType)navigationType {
    
    
    NSString *urlString = _request.URL.absoluteString;
    if ([urlString hasPrefix:@"master:"]) {
        [self pushViewControllerWithUrl:urlString];
        return NO;
    }
//    NSString *requestString = [[_request URL] absoluteString];
//    NSArray *components = [requestString componentsSeparatedByString:@":"];
//    if ([components count] > 1 && [(NSString *)[components objectAtIndex:0]
//                                   isEqualToString:@"myweb"]) {
//        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"touch"])
//        {
//            //NSLog(@"you are touching!");
//            //NSTimeInterval delaytime = Delaytime;
//            if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"start"])
//            {
//                /*
//                 @需延时判断是否响应页面内的js...
//                 */
//                _gesState = GESTURE_STATE_START;
//                NSLog(@"touch start!");
//                
//                float ptX = [[components objectAtIndex:3]floatValue];
//                float ptY = [[components objectAtIndex:4]floatValue];
//                NSLog(@"touch point (%f, %f)", ptX, ptY);
//                
//                NSString *js = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).tagName", ptX, ptY];
//                NSString * tagName = [self.mWebView stringByEvaluatingJavaScriptFromString:js];
//                _imgURL = nil;
//                if ([tagName isEqualToString:@"IMG"]) {
//                    _imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", ptX, ptY];
//                }
//                if (_imgURL) {
//                    _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(handleLongTouch) userInfo:nil repeats:NO];
//                }
//            }
//            else if ([(NSString *)[components objectAtIndex:2] isEqualToString:@"move"])
//            {
//                //**如果touch动作是滑动，则取消hanleLongTouch动作**//
//                _gesState = GESTURE_STATE_MOVE;
//                NSLog(@"you are move");
//            }
//        }
//        else if ([(NSString*)[components objectAtIndex:2]isEqualToString:@"end"]) {
//            [_timer invalidate];
//            _timer = nil;
//            _gesState = GESTURE_STATE_END;
//            NSLog(@"touch end");
//        }
//        return NO;
//    }
    return YES;
//    return [super webView:webView shouldStartLoadWithRequest:_request navigationType:navigationType];
}
// 功能：如果点击的是图片，并且按住的时间超过1s，执行handleLongTouch函数，处理图片的保存操作。
- (void)handleLongTouch {
    NSLog(@"%@", _imgURL);
    if (_imgURL && _gesState == GESTURE_STATE_START) {
        UIActionSheet* sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"保存到手机", nil];
        sheet.cancelButtonIndex = sheet.numberOfButtons - 1;
        [sheet showInView:[UIApplication sharedApplication].keyWindow];
    }
}
// 功能：保存图片到手机
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.numberOfButtons - 1 == buttonIndex) {
        return;
    }
    NSString* title = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([title isEqualToString:@"保存到手机"]) {
        if (_imgURL) {
            NSLog(@"imgurl = %@", _imgURL);
        }
        NSString *urlToSave = [self.mWebView stringByEvaluatingJavaScriptFromString:_imgURL];
        NSLog(@"image url = %@", urlToSave);
        
        NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlToSave]];
        UIImage* image = [UIImage imageWithData:data];
        
        //UIImageWriteToSavedPhotosAlbum(image, nil, nil,nil);
        NSLog(@"UIImageWriteToSavedPhotosAlbum = %@", urlToSave);
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
}
// 功能：显示对话框
-(void)showAlert:(NSString *)msg {
    NSLog(@"showAlert = %@", msg);
    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"提示"
                          message:msg
                          delegate:self
                          cancelButtonTitle:@"确定"
                          otherButtonTitles: nil];
    [alert show];
}
// 功能：显示图片保存结果
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo
{
    if (error){
        NSLog(@"Error");
        [self showAlert:@"保存失败..."];
    }else {
        NSLog(@"OK");
        [self showAlert:@"保存成功！"];
    }
}


@end
